<?php

namespace App\Jobs;

use App\Models\Posts\WxUserCircle;
use App\Models\Circle\WxCircle;
use App\Wen\Utils\UserUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UserPublishedFollowJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $user_id = 0;
    protected $circle_id = 0;
    protected $circle_name = '';
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user_id, $circle_id, $circle_name)
    {
        //
        $this->user_id = $user_id;
        $this->circle_id = $circle_id;
        $this->circle_name = $circle_name;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        if(_empty_($this->user_id) || _empty_($this->circle_id)){
            return;
        }

        if(_empty_($this->circle_name)){
            $this->circle_name = WxCircle::where('id', $this->circle_id)->value('circle_name');
            if(_empty_($this->circle_name)){
                return;
            }
        }

        $user_circlr = WxUserCircle::where([
            ['user_id', '=', $this->user_id],
            ['circle_id', '=', $this->circle_id],
        ])->first();

        if($user_circlr){
            if($user_circlr->user_circle_state == 1){
                // 用户曾经取消关注过
            }
            return;
        }
        $user_circle_model = new WxUserCircle();
        $user_circle_model->user_id = $this->user_id;
        $user_circle_model->circle_id = $this->circle_id;
        $user_circle_model->user_circle_state = 0;
        $user_circle_model->is_read = 0;
        $r = $user_circle_model->save();

        if($r){
            UserUtils::add_user_notice(4007, $this->user_id, '自动关注了「'.$this->circle_name.'」'.env('circle_call', '圈子'),
                '注意到您在「<a href="/pages/circle/list?id='.$this->circle_id.'">'.$this->circle_name.'</a>」'.env('circle_call', '圈子').'发表了笔记，系统已为您自动关注'.env('circle_call', '圈子'), 100);
        }

    }
}
